<template>
  <div class="app-container">
    <!-- <div class="filter-container">
      <el-button size="small" class="filter-item" type="primary" @click="handleFilter">查询</el-button>
      <el-button size="small" class="filter-item" type="danger" icon="el-icon-refresh" @click="handleUpdateVersion">版本更新</el-button>
    </div> -->
    <div class="filter-container">
      <el-form v-model="listQuery" inline>
        <el-form-item label="">
          <el-select
            v-model="listQuery.category_id"
            size="small"
            default-first-option
            style="width: 180px"
            placeholder="能源类型"
            clearable
            @change="change"
          >
            <el-option
              v-for="(item, index) in joinArr"
              :key="index"
              :label="item.name"
              :value="item.category_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="value1"
            size="small"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="listQuery.title"
            size="small"
            style="width: 200px"
            class="filter-item"
            placeholder="能源维度"
            clearable
          />
        </el-form-item>

        <el-form-item label="">
          <!-- <el-input size="small" v-model="listQuery.phone" style="width: 200px" class="filter-item" placeholder="按手机号查询" clearable/>
      <el-select size="small" v-model="listQuery.status" default-first-option style="width: 180px" placeholder="按审核状态查询" clearable>
        <el-option v-for="(item, index) in statusArr" :key="index" :label="item.status" :value="item.value" />
      </el-select> -->
          <el-button
            size="small"
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >
            查询
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            type="warning"
            @click="handleFilter"
          >
            修复
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        key="tableList"
        v-loading="listLoading"
        :data="list"
        element-loading-text="加载中"
        border
        fit
        stripe
        highlight-current-row
        style="width: 100%"
        :header-cell-style="{
          background: '#E3ECFB',
          color: '#303133',
          fontWeight: '500'
        }"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          align="center"
          label="编号 "
          width="150"
          sortable
          prop="number"
        >
          <template slot-scope="scope">
            {{ scope.row.number }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="能耗类型"
          width="170"
          sortable
          prop="created_at"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="地点"
          width="170"
          sortable
          prop="created_at"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.place }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="偏差级别"
          class-name="overflow-on"
        >
          <template slot-scope="scope">
            {{ scope.row.title }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="作者" class-name="overflow-on" width="120">
          <template slot-scope="scope">
            {{ scope.row.author }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column align="center" label="文件地址" class-name="overflow-on" width="120">
          <template slot-scope="scope">
            <el-button plain size="small" @click="downloadfile( scope.row.id )">下载</el-button>

          </template>
        </el-table-column> -->
        <el-table-column align="center" label="偏差值" class-name="overflow-on">
          <template slot-scope="scope">
            {{ scope.row.phone }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="刊登序号" class-name="overflow-on" width="120">
          <template slot-scope="scope">
            {{ scope.row.directory_name }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column align="center" label="封面图" width="100">
          <template slot-scope="scope">
            <el-image style="width: 60px;" :src="scope.row.cover" :preview-src-list="scope.row.imglist"></el-image>
          </template>
        </el-table-column> -->
        <!-- <el-table-column align="center" label="是否置顶" width="100px">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.top" active-color="#13ce66" :inactive-value="0" :active-value="1" inactive-color="grey" @change="changeTopStatus(scope.row,scope.row.top)">
            </el-switch>
          </template>
        </el-table-column> -->

        <!-- <el-table-column align="center" label="审核结果" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status==0 ? 'warning' : (scope.row.status==1 ? 'success' : 'danger')">
              <span>{{ scope.row.status == 0 ? '待审核' :(scope.row.status==1 ? "已通过": "已拒绝") }}</span>
            </el-tag>

          </template>
        </el-table-column> -->

        <el-table-column
          align="center"
          label="上报时间"
          sortable
          prop="updated_at"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.updated_at }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              plain
              type="info"
              size="small"
              @click="updateAction(scope.row.id)"
            >
              查看
            </el-button>

            <el-button
              plain
              v-if="scope.row.status == 0"
              type="warning"
              size="small"
              @click="checkAction(scope.row.id)"
            >
              修复
            </el-button>
            <!-- <el-button plain v-if="scope.row.status == 1" type="primary" size="small" @click="bindAction(scope.row.id,scope.row)"> 登刊信息 </el-button>
            <el-button plain size="small" type="danger" @click="handleDel(scope.row)">删除</el-button> -->

            <!-- <el-button plain v-else-if="scope.row.status == 1" size="small" type="success">已通过</el-button>
            <el-button plain v-else type="danger" size="small"> 已拒绝 </el-button> -->

            <!-- <el-button plain type="success" size="small" @click="openUrlAction(scope.row)" > 查看 </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container text-right">
        <el-pagination
          background
          :total="pagination.total"
          :current-page="listQuery.page"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="800px"
    >
      <template>
        <div class="text-content">
          <div class="text-box">
            <span>投稿时间：{{ temp.created_at }}</span>
          </div>
          <div class="text-box">
            <span>稿件编号：{{ temp.number }}</span>
          </div>

          <div class="text-box">
            <span>作者：{{ temp.author }}</span>
          </div>
          <div class="text-box">
            <span>邮箱：{{ temp.email }}</span>
          </div>
          <div class="text-box">
            <span>电话：{{ temp.phone }}</span>
          </div>
          <div class="text-box" style=" padding :7px;">
            <span
              >文件地址：
              <el-button plain size="small" @click="downloadfile(temp.id)"
                >下载</el-button
              >
            </span>
          </div>

          <div style="padding:20px 0 0 15px;">
            <span>题目：{{ temp.title }}</span>
          </div>
          <el-divider></el-divider>
          <div style="padding:0px 15px;">
            <span>投稿备注信息：{{ temp.msg }}</span>
          </div>
          <el-divider></el-divider>
          <div class="text-box" style="border:0px;font-size:20px;">
            <span style="font-weight:bold;">审核结果</span>
          </div>

          <div class="text-box" style="border:0px;">
            <span></span>
          </div>
          <div class="text-box">
            <span
              >审核状态：
              <span style="font-weight:bold;">{{
                temp.status == 0
                  ? "待审核"
                  : temp.status == 1
                  ? "已通过"
                  : "已拒绝"
              }}</span>
            </span>
          </div>
          <div class="text-box">
            <span>审核时间：{{ temp.check_date }}</span>
          </div>
          <div class="text-box" style="border:0px;">
            <span>审核备注信息：{{ temp.check_msg }}</span>
          </div>
          <el-divider></el-divider>

          <div
            v-if="temp.status == 1"
            class="text-box"
            style="border:0px;font-size:20px;"
          >
            <span style="font-weight:bold;">登刊信息</span>
          </div>
          <div class="text-box" style="border:0px;">
            <span></span>
          </div>
          <div v-if="temp.status == 1" class="text-box">
            <span
              >登刊目录：
              <span style="font-weight:bold;">{{ temp.directory_name }}</span>
            </span>
          </div>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="dialogTitle1"
      :visible.sync="dialogFormVisible1"
      width="700px"
    >
      <el-form
        ref="temp"
        class="small-space"
        :model="temp"
        :rules="rules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="后台备注信息" prop="check_msg">
          <el-input
            type="textarea"
            :rows="5"
            size="small"
            placeholder="该备注信息仅后台可见"
            v-model="temp.check_msg"
            maxlength="32"
            width="100px"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-right">
        <el-button @click="dialogFormVisible1 = false"> 取 消 </el-button>
        <el-button type="success" @click="changeStatus(temp.id, 1)"
          >通过</el-button
        >
        <el-button type="danger" @click="changeStatus(temp.id, 2)"
          >不通过</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :title="dialogTitle2"
      :visible.sync="dialogFormVisible2"
      width="700px"
    >
      <el-form
        ref="temp"
        class="small-space"
        :model="temp"
        :rules="rules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="发布期刊" required>
          <el-select
            size="small"
            v-model="temp.directory_id"
            default-first-option
            style="width: 180px"
            placeholder="选择期刊"
            clearable
          >
            <el-option
              v-for="(item, index) in directoryArr1"
              :key="index"
              :label="item.title"
              :value="item.id"
              :disabled="!item.status"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-right">
        <el-button @click="dialogFormVisible2 = false"> 取 消 </el-button>
        <el-button type="primary" :disabled="btn" @click="handleBind('temp')"
          >确 定</el-button
        >
        <!-- <el-button type="success" @click="changeStatus(temp.id, 1)">通过</el-button>
        <el-button type="danger" @click="changeStatus(temp.id, 2)">拒绝</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getList,
  getAllList,
  create,
  info,
  edit,
  Status,
  topStatus,
  Del,
  BlobFile
} from "@/api/ideas";
import { getToken } from "@/utils/auth";
import { uploadPath } from "@/utils/common";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {}
      },
      mode: "default", // or 'simple'
      btn: false,
      list: null,
      typeList: [],
      uploadPath: uploadPath,
      joinArr: null,
      directoryArr1: null,
      title: null,
      rules: {
        // title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        // content: [{ type: 'string', required: true, message: '请输入内容' }],
      },
      pagination: {},
      listLoading: false,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,

      temp: {},
      listQuery: {
        page: 1,
        limit: 10
      },
      dialogTitle: "",
      dialogTitle1: "",
      dialogTitle2: "",

      header: {
        Authorization: getToken()
      },
      value: "100",
      status: 0,
      content: null,
      origin: null,
      statusArr: [
        { status: "已通过", value: 1 },
        { status: "待审核", value: 0 },
        { status: "已拒绝", value: 2 }
      ]
    };
  },
  created() {
    this.getList();
    //this.getDirectoryList(),
    this.editorConfig.MENU_CONF["uploadImage"] = {
      server: uploadPath,
      fieldName: "file",
      // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 2 * 1024 * 1024, // 2M
      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 10,
      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ["image/*"],
      // 自定义增加 http  header
      headers: {
        Authorization: getToken()
      },
      // 跨域是否传递 cookie ，默认为 false
      withCredentials: false,
      // 超时时间，默认为 10 秒
      timeout: 5 * 1000, // 5 秒
      // 自定义插入图片
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        // 从 res 中找到 url alt href ，然后插图图片
        console.log(res.data.filepath);
        insertFn(res.data.filepath, "", "");
      }
    };
    this.toolbarConfig = {
      excludeKeys: ["insertVideo", "uploadVideo", "group-video"]
    };
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    getList() {
      this.listLoading = true;
      this.list = [
        {
          created_at: "2024-03-05 16:56:56",
          id: 10,
          ip: "117.136.88.26",
          number: "20240305165636",
          phone: "23",
          status: 0,
          title: "严重",
          type: "电",
          place: "a区域",
          updated_at: "2024-03-05 16:56:56"
        },
        {
          created_at: "2024-03-05 16:56:56",
          id: 10,
          ip: "117.136.88.26",
          number: "20240305165636",
          phone: "33",
          status: 0,
          title: "严重",
          type: "电",
          place: "b区域",
          updated_at: "2024-03-05 16:56:56"
        }
      ];
      // getList(this.listQuery).then(response => {
      //   //this.typeList = response.data.typeList

      //   var data = response.data;
      //   this.list = data.data;
      //   this.pagination = data;
      //   //console.log(this.list)
      //   //图片放大处理，声明一个数组，遍历一遍
      //   // this.list.forEach(e => {
      //   //   e.imglist = []
      //   //   e.imglist.push(e.cover)
      //   // });
      // });
      this.listLoading = false;
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },

    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },

    changeTopStatus(row, top) {
      const _this = this;

      topStatus({ id: row.id, top: top }).then(response => {
        row.top = top;

        this.$message.success(response.msg);
        this.getList();
      });
    },

    handleImageSuccess(res, file) {
      if (res.code === 0) {
        this.temp.cover = res.data.filepath;
        //图片相对路径处理
        //this.temp.image_path=process.env.VUE_APP_BASE_PIC +  this.temp.image_path
        this.temp.cover = this.temp.cover;
        // uploadPath = uploadPath.this.temp.image_path;

        this.$message.success("上传成功！");
      } else {
        this.$message.error(res.msg);
      }
    },
    downloadfile(id) {
      //这里下载的是时间戳格式的文件，后端会重新命名处理。
      //console.log(id);
      //window.location.href = id;
      BlobFile({ id: id }).then(res => {
        //console.log(res);
        if (res.code == 0) {
          window.location.href = res.data;
        } else {
          this.$message.error(res.msg); // 将错误信息显示出来
        }
        //   // 处理下载失败的问题，data是得到的请求结果
        //if (res.type === 'application/json') {
        //     const reader = new FileReader()
        //     reader.onload = function () {
        //       const message = JSON.parse(reader.result).bizMsg
        //       Message.error(message) // 将错误信息显示出来
        //     }
        //     reader.readAsText(res)
        //     return
        // }
        //   const blob = new Blob([res], { type: 'application/msword' })
        //   const a = document.createElement('a')
        //   const href = window.URL.createObjectURL(blob) // 创建下载的链接
        //   a.href = href
        //   const filename = '111'
        //   a.download = filename // 下载后文件名
        //   document.body.appendChild(a)
        //   a.click() // 点击下载
        //   document.body.removeChild(a) // 下载完成移除元素
        //   window.URL.revokeObjectURL(href) // 释放掉blob对象
      });
    },

    changeStatus(row, status) {
      this.tishi_msg = status == 1 ? "审核通过" : "拒绝";
      //console.log(this.temp.check_msg);
      this.$confirm(
        " 此操作将【" + this.tishi_msg + "】该投稿, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          Status({
            id: row,
            status: status,
            check_msg: this.temp.check_msg
          }).then(response => {
            //row.status = status;
            this.$message.success(response.msg);
            this.dialogFormVisible1 = !this.dialogFormVisible1;
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作"
          });
        });
    },

    // openUrlAction(val){
    //   if(val.type == 0){
    //     // 默认
    //     let routeUrl = '/protocol?id=' + val.id;
    //     window.open(routeUrl, '_blank')
    //   }else if(val.type == 1){
    //     //隐私
    //     let routeUrl = '/protocol/privacy?body=' + val.main_body;
    //     window.open(routeUrl, '_blank')
    //   }else if(val.type == 2){
    //     //用户
    //     let routeUrl = '/protocol/user?body=' + val.main_body;
    //     window.open(routeUrl, '_blank')
    //   }else{
    //     let routeUrl = '/protocol/child?body=' + val.main_body;
    //     window.open(routeUrl, '_blank')
    //   }
    // },

    doAdd() {
      create(this.temp).then(res => {
        if (res.code === 0) {
          this.$message.success("添加成功！");
          this.getList();
          this.dialogFormVisible = !this.dialogFormVisible;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleSave(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // this.btn = true;
          if (this.dialogTitle === "添加") {
            this.doAdd();
          } else {
            edit(this.temp).then(res => {
              this.btn = false;
              if (res.code === 0) {
                this.$message.success(res.msg);
                this.getList();
                this.dialogFormVisible = !this.dialogFormVisible;
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: "请检查输入是否正确",
            offset: 100
          });
          return false;
        }
      });
    },

    handleBind(formName) {
      edit({ id: this.temp.id, directory_id: this.temp.directory_id }).then(
        res => {
          this.btn = false;
          if (res.code === 0) {
            this.$message.success(res.msg);
            this.getList();
            this.dialogFormVisible2 = !this.dialogFormVisible2;
          } else {
            this.$message.error(res.msg);
          }
        }
      );
    },

    updateAction(id) {
      info({ id: id }).then(res => {
        if (res.code === 0) {
          this.btn = false;
          this.temp = res.data;
          //console.log(this.temp)
          this.dialogTitle = "投稿信息";
          this.dialogFormVisible = !this.dialogFormVisible;
        } else {
          this.$message.error(res.msg);
        }
      });
      // getAllList(this.listQuery).then((response) => {
      //   var data = response.data;
      //   console.log(data);
      //   this.joinArr = data;
      // })
    },

    /**
     * 审核
     */
    checkAction(id) {
      info({ id: id }).then(res => {
        if (res.code === 0) {
          this.btn = false;
          this.temp = res.data;
          this.dialogTitle1 = "审核";
          this.dialogFormVisible1 = !this.dialogFormVisible1;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    bindAction(id, row) {
      this.dialogTitle2 = "绑定登刊信息";
      this.temp = row;
      getAllList().then(res => {
        if (res.code === 0) {
          this.btn = false;
          this.directoryArr1 = res.data;
          this.dialogFormVisible2 = !this.dialogFormVisible2;
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    showCreate() {
      this.temp = {
        title: null,
        cover: "",
        origin: "",
        cover: "",
        startTime: "",
        status: 0
      };
      this.btn = false;
      this.dialogTitle = "添加";
      this.dialogFormVisible = !this.dialogFormVisible;
    },
    handleDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // console.log(row.id);
          Del({ id: row.id }).then(response => {
            if (response.code === 0) {
              this.$message({
                message: response.msg,
                type: "success"
              });
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
    // handleImageSuccess(res, file) {
    //   if (res.code === 0) {
    //     this.temp.cover =res.data.filepath;
    //     //图片相对路径处理
    //    //this.temp.image_path=process.env.VUE_APP_BASE_PIC +  this.temp.image_path
    //    this.temp.cover=this.temp.cover
    //    // uploadPath = uploadPath.this.temp.image_path;

    //     this.$message.success('上传成功！')
    //   } else {
    //     this.$message.error(res.msg)
    //   }
    // },
  }
};
</script>

<style scoped>
.overflow-on .cell {
  overflow: visible;
  overflow-x: visible;
  overflow-y: visible;
}
/* .table-container {
  margin: 20px 0;
} */
.ql-editor {
  height: 360px;
}
.text-content {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.text-box {
  width: 50%;
  padding: 15px;
  border-bottom: 1px solid #dcdfe6;
}
.el-dialog__title {
  font-weight: bold;
  padding-left: 10px;
  font-size: 20px;
}
.el-dialog__body {
  padding: 10px 20px 20px 30px;
}
</style>
